<template>
  <div class="project-detail-container">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/" style="margin: 20px 0;">
      <el-breadcrumb-item :to="{ path: '/project-manage' }">项目管理</el-breadcrumb-item>
      <el-breadcrumb-item>{{ projectInfo.name || '项目详情' }}</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 项目基础信息 -->
    <el-card shadow="hover" class="project-info-card">
      <div class="project-info-header">
        <div class="project-title">
          <el-icon class="project-icon"><Folder /></el-icon>
          <h2>{{ projectInfo.name }}</h2>
          <el-button 
            type="text" 
            size="small" 
            @click="openEditProjectDialog"
            style="margin-left: 20px;"
          >
            <el-icon><Edit /></el-icon> 编辑项目
          </el-button>
        </div>
        <div class="project-actions">
          <el-button type="primary" size="small" @click="openAddCaseDialog">
            <el-icon><Plus /></el-icon> 新增用例
          </el-button>
          <el-button type="success" size="small" style="margin-left: 10px;" @click="runAllCases">
            <el-icon><Play /></el-icon> 执行全部用例
          </el-button>
        </div>
      </div>

      <div class="project-meta">
        <div class="meta-item">
          <span class="meta-label">负责人：</span>
          <span>{{ projectInfo.owner || '未设置' }}</span>
        </div>
        <div class="meta-item">
          <span class="meta-label">创建人：</span>
          <span>{{ projectInfo.creator || '未知' }}</span>
        </div>
        <div class="meta-item">
          <span class="meta-label">创建时间：</span>
          <span>{{ formatTime(projectInfo.create_time) }}</span>
        </div>
        <div class="meta-item">
          <span class="meta-label">最后更新：</span>
          <span>{{ formatTime(projectInfo.update_time) }}</span>
        </div>
      </div>

      <div class="project-description">
        <h3>项目描述</h3>
        <p>{{ projectInfo.description || '无描述信息' }}</p>
      </div>

      <!-- 项目统计卡片 -->
      <div class="project-stats">
        <el-card class="stat-card">
          <div class="stat-label">用例总数</div>
          <div class="stat-value">{{ projectStats.case_count || 0 }}</div>
        </el-card>
        <el-card class="stat-card success">
          <div class="stat-label">通过用例</div>
          <div class="stat-value">{{ projectStats.success_count || 0 }}</div>
        </el-card>
        <el-card class="stat-card danger">
          <div class="stat-label">失败用例</div>
          <div class="stat-value">{{ projectStats.fail_count || 0 }}</div>
        </el-card>
        <el-card class="stat-card">
          <div class="stat-label">最新通过率</div>
          <div class="stat-value">{{ projectStats.latest_pass_rate || 0 }}%</div>
        </el-card>
      </div>
    </el-card>

    <!-- 标签页：用例/报告/成员 -->
    <el-tabs v-model="activeTab" type="card" style="margin-top: 20px;">
      <!-- 项目用例列表 -->
      <el-tab-pane label="用例列表" name="cases">
        <el-card shadow="hover">
          <div class="case-search">
            <el-input
              v-model="caseSearchKey"
              placeholder="搜索用例名称"
              size="small"
              style="width: 300px;"
              @keyup.enter="getProjectCases"
            >
              <template #append>
                <el-button size="small" type="primary" @click="getProjectCases">
                  <el-icon><Search /></el-icon>
                </el-button>
              </template>
            </el-input>
          </div>

          <el-table
            v-loading="casesLoading"
            :data="projectCases"
            border
            stripe
            size="small"
            style="width: 100%; margin-top: 10px;"
          >
            <el-table-column prop="id" label="用例ID" width="80" align="center" />
            <el-table-column prop="case_name" label="用例名称" align="center" />
            <el-table-column prop="api_url" label="接口URL" align="center" width="250" />
            <el-table-column prop="method" label="请求方式" align="center" width="100">
              <template #default="scope">
                <el-tag :type="scope.row.method === 'GET' ? 'info' : 'primary'">
                  {{ scope.row.method }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="最近执行结果" align="center" width="120">
              <template #default="scope">
                <el-tag :type="scope.row.latest_result === 'success' ? 'success' : 'danger'">
                  {{ scope.row.latest_result || '未执行' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="180">
              <template #default="scope">
                <el-button type="text" size="small" @click="editCase(scope.row)">编辑</el-button>
                <el-button type="text" size="small" @click="runCase(scope.row.id)">执行</el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-pagination
            @size-change="handleCaseSizeChange"
            @current-change="handleCaseCurrentChange"
            :current-page="casePage"
            :page-sizes="[10, 20, 50]"
            :page-size="caseLimit"
            layout="total, sizes, prev, pager, next, jumper"
            :total="caseTotal"
            style="margin-top: 15px; text-align: right;"
          />
        </el-card>
      </el-tab-pane>

      <!-- 项目报告列表 -->
      <el-tab-pane label="测试报告" name="reports">
        <el-card shadow="hover">
          <el-table
            v-loading="reportsLoading"
            :data="projectReports"
            border
            stripe
            size="small"
            style="width: 100%;"
          >
            <el-table-column prop="id" label="报告ID" width="80" align="center" />
            <el-table-column prop="report_name" label="报告名称" align="center" />
            <el-table-column label="执行时间" align="center" width="180">
              <template #default="scope">{{ formatTime(scope.row.create_time) }}</template>
            </el-table-column>
            <el-table-column label="用例数" align="center" width="100">
              <template #default="scope">{{ scope.row.total_cases }}</template>
            </el-table-column>
            <el-table-column label="通过率" align="center" width="120">
              <template #default="scope">
                <el-progress
                  :percentage="scope.row.pass_rate"
                  :stroke-width="6"
                  :format="(p) => `${p}%`"
                  style="width: 100px;"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="120">
              <template #default="scope">
                <el-button type="text" size="small" @click="previewReport(scope.row.id)">预览</el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-pagination
            @size-change="handleReportSizeChange"
            @current-change="handleReportCurrentChange"
            :current-page="reportPage"
            :page-sizes="[10, 20, 50]"
            :page-size="reportLimit"
            layout="total, sizes, prev, pager, next, jumper"
            :total="reportTotal"
            style="margin-top: 15px; text-align: right;"
          />
        </el-card>
      </el-tab-pane>

      <!-- 项目成员管理 -->
      <el-tab-pane label="项目成员" name="members">
        <el-card shadow="hover">
          <div class="member-actions" style="margin-bottom: 15px;">
            <el-button type="primary" size="small" @click="openAddMemberDialog">
              <el-icon><Plus /></el-icon> 添加成员
            </el-button>
          </div>

          <el-table
            v-loading="membersLoading"
            :data="projectMembers"
            border
            stripe
            size="small"
            style="width: 100%;"
          >
            <el-table-column prop="username" label="用户名" align="center" />
            <el-table-column prop="role" label="角色" align="center" width="150">
              <template #default="scope">
                <el-select
                  v-model="scope.row.role"
                  size="small"
                  @change="changeMemberRole(scope.row.id, scope.row.role)"
                >
                  <el-option label="管理员" value="admin" />
                  <el-option label="测试员" value="tester" />
                  <el-option label="只读" value="viewer" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="join_time" label="加入时间" align="center" width="180">
              <template #default="scope">{{ formatTime(scope.row.join_time) }}</template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="120">
              <template #default="scope">
                <el-button
                  type="text"
                  size="small"
                  text-color="#f56c6c"
                  @click="removeMember(scope.row.id)"
                  v-if="scope.row.username !== projectInfo.creator"
                >
                  移除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-tab-pane>
    </el-tabs>

    <!-- 编辑项目弹窗（复用项目管理页的逻辑） -->
    <el-dialog
      v-model="editProjectVisible"
      title="编辑项目"
      width="500px"
    >
      <el-form
        ref="editProjectFormRef"
        :model="editProjectForm"
        :rules="projectRules"
        label-width="100px"
      >
        <el-form-item label="项目名称" prop="name">
          <el-input v-model="editProjectForm.name" />
        </el-form-item>
        <el-form-item label="项目描述" prop="description">
          <el-input v-model="editProjectForm.description" type="textarea" rows="3" />
        </el-form-item>
        <el-form-item label="负责人" prop="owner">
          <el-input v-model="editProjectForm.owner" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editProjectVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEditProject">确认</el-button>
      </template>
    </el-dialog>

    <!-- 新增用例弹窗（简化版，复用用例管理页逻辑） -->
    <el-dialog
      v-model="addCaseVisible"
      title="新增项目用例"
      width="600px"
    >
      <el-form
        ref="caseFormRef"
        :model="caseForm"
        :rules="caseRules"
        label-width="120px"
      >
        <el-form-item label="用例名称" prop="case_name">
          <el-input v-model="caseForm.case_name" />
        </el-form-item>
        <el-form-item label="接口URL" prop="api_url">
          <el-input v-model="caseForm.api_url" />
        </el-form-item>
        <el-form-item label="请求方式" prop="method">
          <el-select v-model="caseForm.method">
            <el-option label="GET" value="GET" />
            <el-option label="POST" value="POST" />
          </el-select>
        </el-form-item>
        <el-form-item label="请求参数" prop="params">
          <el-input v-model="caseForm.params" type="textarea" rows="4" />
        </el-form-item>
        <el-form-item label="预期结果" prop="expected_result">
          <el-input v-model="caseForm.expected_result" type="textarea" rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addCaseVisible = false">取消</el-button>
        <el-button type="primary" @click="submitCaseForm">确认</el-button>
      </template>
    </el-dialog>

    <!-- 添加成员弹窗 -->
    <el-dialog
      v-model="addMemberVisible"
      title="添加项目成员"
      width="400px"
    >
      <el-form
        ref="memberFormRef"
        :model="memberForm"
        :rules="memberRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="memberForm.username" placeholder="请输入要添加的用户名" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="memberForm.role" placeholder="请选择角色">
            <el-option label="管理员" value="admin" />
            <el-option label="测试员" value="tester" />
            <el-option label="只读" value="viewer" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addMemberVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAddMember">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, ElTag, ElProgress, ElIcon } from 'element-plus'
import { Folder, Edit, Plus, Play, Search } from '@element-plus/icons-vue'
import request from '@/api/request'

// 路由参数（项目ID）
const route = useRoute()
const router = useRouter()
const projectId = ref(route.params.id || '')

// 项目基础信息
const projectInfo = reactive({
  name: '',
  description: '',
  owner: '',
  creator: '',
  create_time: '',
  update_time: ''
})

// 项目统计数据
const projectStats = reactive({
  case_count: 0,
  success_count: 0,
  fail_count: 0,
  latest_pass_rate: 0
})

// 标签页状态
const activeTab = ref('cases')

// 用例列表相关
const projectCases = ref([])
const casePage = ref(1)
const caseLimit = ref(10)
const caseTotal = ref(0)
const casesLoading = ref(false)
const caseSearchKey = ref('')

// 报告列表相关
const projectReports = ref([])
const reportPage = ref(1)
const reportLimit = ref(10)
const reportTotal = ref(0)
const reportsLoading = ref(false)

// 成员列表相关
const projectMembers = ref([])
const membersLoading = ref(false)

// 弹窗状态
const editProjectVisible = ref(false)
const addCaseVisible = ref(false)
const addMemberVisible = ref(false)

// 编辑项目表单
const editProjectForm = reactive({
  id: '',
  name: '',
  description: '',
  owner: ''
})
const projectRules = reactive({
  name: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
  owner: [{ required: true, message: '请输入负责人', trigger: 'blur' }]
})
const editProjectFormRef = ref(null)

// 新增用例表单
const caseForm = reactive({
  case_name: '',
  api_url: '',
  method: 'GET',
  params: '',
  expected_result: '',
  project_id: projectId.value // 绑定当前项目ID
})
const caseRules = reactive({
  case_name: [{ required: true, message: '请输入用例名称', trigger: 'blur' }],
  api_url: [{ required: true, message: '请输入接口URL', trigger: 'blur' }],
  method: [{ required: true, message: '请选择请求方式', trigger: 'change' }],
  expected_result: [{ required: true, message: '请输入预期结果', trigger: 'blur' }]
})
const caseFormRef = ref(null)

// 添加成员表单
const memberForm = reactive({
  username: '',
  role: 'tester'
})
const memberRules = reactive({
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  role: [{ required: true, message: '请选择角色', trigger: 'change' }]
})
const memberFormRef = ref(null)

// 页面挂载时加载数据
onMounted(() => {
  if (!projectId.value) {
    ElMessage.error('项目ID无效')
    router.push('/project-manage')
    return
  }
  loadProjectData()
})

// 监听项目ID变化（如路由参数更新）
watch(() => route.params.id, (newId) => {
  projectId.value = newId
  loadProjectData()
})

// 加载项目所有数据
const loadProjectData = () => {
  getProjectInfo()
  getProjectStats()
  getProjectCases()
  getProjectReports()
  getProjectMembers()
}

// 1. 获取项目基础信息
const getProjectInfo = async () => {
  try {
    const res = await request.get(`/api/projects/${projectId.value}/`)
    Object.assign(projectInfo, res.data)
    // 初始化编辑表单
    editProjectForm.id = projectId.value
    editProjectForm.name = res.data.name
    editProjectForm.description = res.data.description
    editProjectForm.owner = res.data.owner
  } catch (error) {
    ElMessage.error('获取项目信息失败：' + (error.response?.data?.msg || error.message))
  }
}

// 2. 获取项目统计数据
const getProjectStats = async () => {
  try {
    const res = await request.get(`/api/projects/${projectId.value}/stats/`)
    Object.assign(projectStats, res.data)
  } catch (error) {
    console.error('获取项目统计失败', error)
  }
}

// 3. 获取项目用例列表
const getProjectCases = async () => {
  casesLoading.value = true
  try {
    const res = await request.get(`/api/projects/${projectId.value}/cases/`, {
      params: {
        page: casePage.value,
        limit: caseLimit.value,
        search: caseSearchKey.value
      }
    })
    projectCases.value = res.data?.list || []
    caseTotal.value = res.data?.total || 0
  } catch (error) {
    ElMessage.error('获取用例列表失败：' + (error.response?.data?.msg || error.message))
  } finally {
    casesLoading.value = false
  }
}

// 4. 获取项目报告列表
const getProjectReports = async () => {
  reportsLoading.value = true
  try {
    const res = await request.get(`/api/projects/${projectId.value}/reports/`, {
      params: {
        page: reportPage.value,
        limit: reportLimit.value
      }
    })
    projectReports.value = res.data?.list || []
    reportTotal.value = res.data?.total || 0
  } catch (error) {
    ElMessage.error('获取报告列表失败：' + (error.response?.data?.msg || error.message))
  } finally {
    reportsLoading.value = false
  }
}

// 5. 获取项目成员列表
const getProjectMembers = async () => {
  membersLoading.value = true
  try {
    const res = await request.get(`/api/projects/${projectId.value}/members/`)
    projectMembers.value = res.data || []
  } catch (error) {
    ElMessage.error('获取成员列表失败：' + (error.response?.data?.msg || error.message))
  } finally {
    membersLoading.value = false
  }
}

// 6. 编辑项目提交
const submitEditProject = async () => {
  const valid = await editProjectFormRef.value.validate()
  if (!valid) return

  try {
    await request.put(`/api/projects/${projectId.value}/`, editProjectForm)
    ElMessage.success('项目编辑成功')
    editProjectVisible.value = false
    getProjectInfo() // 刷新项目信息
  } catch (error) {
    ElMessage.error('编辑失败：' + (error.response?.data?.msg || error.message))
  }
}

// 7. 新增用例提交
const submitCaseForm = async () => {
  const valid = await caseFormRef.value.validate()
  if (!valid) return

  try {
    // 绑定项目ID
    caseForm.project_id = projectId.value
    await request.post('/api/case/', caseForm)
    ElMessage.success('用例新增成功')
    addCaseVisible.value = false
    getProjectCases() // 刷新用例列表
    getProjectStats() // 刷新统计数据
    // 重置表单
    caseForm.case_name = ''
    caseForm.api_url = ''
    caseForm.params = ''
    caseForm.expected_result = ''
  } catch (error) {
    ElMessage.error('新增失败：' + (error.response?.data?.msg || error.message))
  }
}

// 8. 执行单个用例
const runCase = async (caseId) => {
  try {
    await request.post(`/api/case/${caseId}/run/`)
    ElMessage.success('用例执行中，请查看日志')
  } catch (error) {
    ElMessage.error('执行失败：' + (error.response?.data?.msg || error.message))
  }
}

// 9. 执行全部用例
const runAllCases = async () => {
  try {
    await request.post(`/api/projects/${projectId.value}/run-all/`)
    ElMessage.success('全部用例开始执行，完成后将生成测试报告')
  } catch (error) {
    ElMessage.error('执行失败：' + (error.response?.data?.msg || error.message))
  }
}

// 10. 添加项目成员
const submitAddMember = async () => {
  const valid = await memberFormRef.value.validate()
  if (!valid) return

  try {
    await request.post(`/api/projects/${projectId.value}/members/`, memberForm)
    ElMessage.success('成员添加成功')
    addMemberVisible.value = false
    getProjectMembers() // 刷新成员列表
    // 重置表单
    memberForm.username = ''
    memberForm.role = 'tester'
  } catch (error) {
    ElMessage.error('添加失败：' + (error.response?.data?.msg || error.message))
  }
}

// 11. 修改成员角色
const changeMemberRole = async (memberId, newRole) => {
  try {
    await request.put(`/api/projects/${projectId.value}/members/${memberId}/`, {
      role: newRole
    })
    ElMessage.success('角色修改成功')
  } catch (error) {
    ElMessage.error('修改失败：' + (error.response?.data?.msg || error.message))
    // 失败时回滚显示
    getProjectMembers()
  }
}

// 12. 移除项目成员
const removeMember = async (memberId) => {
  ElMessageBox.confirm(
    '确认移除该成员吗？',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await request.delete(`/api/projects/${projectId.value}/members/${memberId}/`)
      ElMessage.success('成员已移除')
      getProjectMembers()
    } catch (error) {
      ElMessage.error('移除失败：' + (error.response?.data?.msg || error.message))
    }
  }).catch(() => {
    ElMessage.info('已取消移除')
  })
}

// 13. 预览报告（跳转到报告中心并定位）
const previewReport = (reportId) => {
  router.push(`/report-center?reportId=${reportId}`)
}

// 14. 编辑用例（跳转到用例管理并定位）
const editCase = (row) => {
  router.push(`/case-manage?editCaseId=${row.id}`)
}

// 分页相关方法
const handleCaseSizeChange = (val) => {
  caseLimit.value = val
  casePage.value = 1
  getProjectCases()
}
const handleCaseCurrentChange = (val) => {
  casePage.value = val
  getProjectCases()
}
const handleReportSizeChange = (val) => {
  reportLimit.value = val
  reportPage.value = 1
  getProjectReports()
}
const handleReportCurrentChange = (val) => {
  reportPage.value = val
  getProjectReports()
}

// 工具函数：格式化时间
const formatTime = (timeStr) => {
  if (!timeStr) return '未知'
  try {
    const date = new Date(timeStr)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    }).replace(/\//g, '-')
  } catch (error) {
    return timeStr
  }
}
</script>

<style scoped lang="scss">
.project-detail-container {
  padding: 0 20px 20px;
}

// 项目信息卡片样式
.project-info-card {
  .project-info-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    .project-title {
      display: flex;
      align-items: center;
      h2 {
        margin: 0 10px;
        font-size: 18px;
        color: #333;
      }
      .project-icon {
        font-size: 24px;
        color: #4361ee;
      }
    }
  }

  .project-meta {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px dashed #eee;
    .meta-item {
      font-size: 14px;
      .meta-label {
        color: #666;
        font-weight: 500;
      }
    }
  }

  .project-description {
    margin-bottom: 20px;
    h3 {
      margin: 0 0 10px;
      font-size: 16px;
      color: #333;
    }
    p {
      margin: 0;
      color: #666;
      line-height: 1.6;
    }
  }

  .project-stats {
    display: flex;
    gap: 15px;
    .stat-card {
      flex: 1;
      text-align: center;
      padding: 15px 0;
      .stat-label {
        font-size: 14px;
        color: #666;
        margin-bottom: 5px;
      }
      .stat-value {
        font-size: 22px;
        font-weight: bold;
        color: #333;
      }
      &.success .stat-value {
        color: #67c23a;
      }
      &.danger .stat-value {
        color: #f56c6c;
      }
    }
  }
}

// 用例搜索样式
.case-search {
  display: flex;
  justify-content: flex-start;
}
</style>